"use client";
import React, { useState } from 'react';
import  './index.css';
const CopyUrlButton = () => {
    const [isCopied, setIsCopied] = useState(false);

    const copyToClipboard = async () => {
        const url = window.location.href;
        try {
            // 使用现代 Clipboard API
            await navigator.clipboard.writeText(url);
            setIsCopied(true);
        } catch (err) {
            // 回退到老方法
            const textArea = document.createElement('textarea');
            textArea.value = url;
            document.body.appendChild(textArea);
            textArea.select();
            try {
                document.execCommand('copy');
                setIsCopied(true);
            } catch (err) {
                console.error('复制失败:', err);
            }
            document.body.removeChild(textArea);
        }
        // 3秒后隐藏提示
        setTimeout(() => setIsCopied(false), 3000);
    };

    return (
        <div className="container">
            <button className="copyButton" onClick={copyToClipboard}>复制分享链接</button>
            {isCopied && <div className='successMessage'>链接已复制！</div>}
        </div>
    );
};

export default CopyUrlButton;